import React, {useContext} from 'react';
import translations from '../i18n/i18nText';
import {useSystemStore} from '@/stores';

type TranslationType = {
  [key: string]: {
    [key: string]: {
      [key: string]: string;
    };
  };
};

const I18nContext = React.createContext<{
  lang: keyof typeof translations;
  translations: TranslationType;
}>({
  lang: 'zh-cn',
  translations,
});

export const I18nProvider = ({children}: {children: React.ReactNode}) => {
  const systemStore = useSystemStore();

  return (
    <I18nContext.Provider
      value={{
        lang: systemStore.state.lang as keyof typeof translations,
        translations,
      }}>
      {children}
    </I18nContext.Provider>
  );
};

export const useI18n = () => {
  const {lang, translations} = useContext(I18nContext);

  const t = (keys: string) => {
    if (!keys) {
      return keys;
    }
    const [module, key] = keys.split('.');
    return translations[lang]?.[module]?.[key] || keys;
  };

  return {t};
};
